package com.ruoyi.common.utils.echarts;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.beyongx.echarts.charts.custom.ItemStyle;
import com.beyongx.echarts.options.XAxis;
import com.github.abel533.echarts.DataZoom;
import com.github.abel533.echarts.Grid;
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.axis.Axis;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.code.AxisType;
import com.github.abel533.echarts.code.DataZoomType;
import com.github.abel533.echarts.code.SeriesType;
import com.github.abel533.echarts.series.Line;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.phantomjs.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.ClientProtocolException;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chmj
 * @version V1.0
 * @Package com.ruoyi.common.utils
 * @Copyright 2022/9/28 18:40 汇博医疗股份有限公司
 */
@Slf4j
public class EchartsUtil {

    public static String createLine(String title, Integer minY, List<String> dataX, List<Integer> dataY) throws ClientProtocolException, IOException {
        Option option = new Option();
        option.title(title);
//        Grid gird = new Grid();
//        gird.left("20%");
//        gird.right("20%");
//        gird.bottom("20%");
//        gird.containLabel(true);
//        option.grid(gird);
//        List<DataZoom> dataZoomList = new ArrayList<>();
//        DataZoom dataZoom1 = new DataZoom();
//        dataZoom1.show(true);
//        dataZoom1.realtime(true);
//        dataZoom1.start(0);
//        dataZoom1.end(100);
//        dataZoomList.add(dataZoom1);
//        DataZoom dataZoom2 = new DataZoom();
//        dataZoom2.type(DataZoomType.inside);
//        dataZoom2.realtime(true);
//        dataZoom2.start(0);
//        dataZoom2.end(100);
//        dataZoomList.add(dataZoom2);
//        option.dataZoom(dataZoomList);
        CategoryAxis xAxis = new CategoryAxis();
        xAxis.setData(dataX);
        xAxis.type(AxisType.category);
        option.xAxis(xAxis);

        CategoryAxis yAxis = new CategoryAxis();
        yAxis.min(minY);
        yAxis.type(AxisType.value);
        option.yAxis(yAxis);
        Line line = new Line();
        line.type(SeriesType.line);
        line.name(title);
//        line.data(dataY);
        line.setData(dataY);
        option.series(line);
        return createImage(JSONObject.toJSONString(option));
    }

    public static String createCustom(String title, List<Map<String,Object>> legends, List<String> dataY, Long minX, List<Map<String,Object>> typeItem, List<Long> duration) throws ClientProtocolException, IOException {
//        Option option = new Option();
//        option.title(title);
//        Grid gird = new Grid();
//        gird.left("20%");
//        gird.right("20%");
//        gird.bottom("20%");
//        gird.containLabel(true);
//        option.grid(gird);
//        List<DataZoom> dataZoomList = new ArrayList<>();
//        DataZoom dataZoom1 = new DataZoom();
//        dataZoom1.show(true);
//        dataZoom1.realtime(true);
//        dataZoom1.start(0);
//        dataZoom1.end(100);
//        dataZoomList.add(dataZoom1);
//        DataZoom dataZoom2 = new DataZoom();
//        dataZoom2.type(DataZoomType.inside);
//        dataZoom2.realtime(true);
//        dataZoom2.start(0);
//        dataZoom2.end(100);
//        dataZoomList.add(dataZoom2);
//        option.dataZoom(dataZoomList);
//        CategoryAxis xAxis = new CategoryAxis();
//        Map<String,Object> xAxisMap = new HashMap<>();
//        xAxisMap.put("scale",true);
//        xAxisMap.put("min",minX);
//        Map<String,Object> axisLabelMap = new HashMap<>();
//        axisLabelMap.put("color","#333");
//        axisLabelMap.put("formatter","function (param) {let date = new Date(param);let dateLabel = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+' '+date.getHours()+':'+date.getMinutes()+':'+date.getSeconds();return dateLabel;}");
//        xAxisMap.put("axisLabel",axisLabelMap);
//        xAxis.min(minX);
//        xAxis.scale(true);
//        option.xAxis(xAxis);
//        CategoryAxis yAxis = new CategoryAxis();
//        yAxis.setData(dataY);
//        option.yAxis(yAxis);
//
//        List<Map<String,Object>> dataList = new ArrayList<>();
//        for (int i = 0; i < dataY.size(); i++) {
//            Long baseTime = minX;
//            for (int j = 0; j < duration.size(); j++) {
//                Map<String,Object> dataMap = new HashMap<>();
//                dataMap.put("name",typeItem.get(j).get("name"));
//                List<Long> valueList = new ArrayList<>();
//                valueList.add(Long.valueOf(i));
//                valueList.add(baseTime);
//                valueList.add(baseTime += duration.get(j));
//                valueList.add(duration.get(j));
//                dataMap.put("value",valueList);
//                Map<String,Object> itemStyleMap = new HashMap<>();
//                Map<String,Object> normalMap = new HashMap<>();
//                normalMap.put("color",typeItem.get(j).get("color"));
//                itemStyleMap.put("normal",normalMap);
//                dataMap.put("itemStyle",itemStyleMap);
//                dataList.add(dataMap);
//            }
//        }

        com.beyongx.echarts.Option option = new com.beyongx.echarts.Option();
        com.beyongx.echarts.options.Title beTitle = new com.beyongx.echarts.options.Title();
        beTitle.setText(title);
        option.title(beTitle);

        com.beyongx.echarts.options.XAxis xAxis = new com.beyongx.echarts.options.XAxis();
        xAxis.setMin(minX);
        xAxis.setScale("true"); //["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
        Map<String, Object> axisLabel = new HashMap<>();
        axisLabel.put("color","#333");
        xAxis.setAxisLabel(axisLabel);
        option.xAxis(xAxis);

        com.beyongx.echarts.options.YAxis yAxis = new com.beyongx.echarts.options.YAxis();
        yAxis.setData(dataY.toArray());
        option.yAxis(yAxis);

        List<Map<String,Object>> dataList = new ArrayList<>();
        for (int i = 0; i < dataY.size(); i++) {
            Long baseTime = minX;
            for (int j = 0; j < duration.size(); j++) {
                Map<String,Object> dataMap = new HashMap<>();
                dataMap.put("name",typeItem.get(j).get("name"));
                List<Long> valueList = new ArrayList<>();
                valueList.add(Long.valueOf(j));
                valueList.add(baseTime);
                valueList.add(baseTime += duration.get(j));
                valueList.add(duration.get(j));
                dataMap.put("value",valueList);
                Map<String,Object> itemStyleMap = new HashMap<>();
                Map<String,Object> normalMap = new HashMap<>();
                normalMap.put("color",typeItem.get(j).get("color"));
                itemStyleMap.put("normal",normalMap);
                dataMap.put("itemStyle",itemStyleMap);
                dataList.add(dataMap);
            }
        }
        String renderItem = "(params, api) => { var categoryIndex = api.value(0); var start = api.coord([api.value(1), categoryIndex]); var end = api.coord([api.value(2), categoryIndex]); var height = api.size([0, 1])[1] * 0.6; var rectShape = echarts.graphic.clipRectByRect( { x: start[0], y: start[1] - height / 2, width: end[0] - start[0], height: height }, { x: params.coordSys.x, y: params.coordSys.y, width: params.coordSys.width, height: params.coordSys.height } ); return ( rectShape && { type: 'rect', transition: ['shape'], shape: rectShape, style: api.style() } ); }";
        for (Map<String,Object> legend:legends) {
            com.beyongx.echarts.charts.Custom custom = new com.beyongx.echarts.charts.Custom();
            custom.setData(dataY.toArray());
            custom.setName(legend.get("name").toString());
            custom.setType("custom");
            custom.setRenderItem(renderItem);
            Map<String,Object> itemStyleMap = new HashMap<>();
            itemStyleMap.put("opacity",0.8);
            Map<String,Object> normalMap = new HashMap<>();
            normalMap.put("color",legend.get("color"));
            itemStyleMap.put("normal",normalMap);
            custom.setItemStyle(itemStyleMap);
            Map<String,Object> encodeMap = new HashMap<>();
            List<Integer> xList = new ArrayList<>();
            xList.add(1);
            xList.add(2);
            encodeMap.put("x",xList);
            encodeMap.put("y",0);
            custom.setEncode(encodeMap);
            custom.setData(dataList.toArray());
            option.addSeries(custom);
        }
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        return createImage(gson.toJson(option));
        // 模板参数
//        HashMap<String, Object> data = new HashMap<>();
//        data.put("title", title);
//        data.put("minX", minX);
//        data.put("yAxis", JSON.toJSONString(dataY));
//        for (int i = 0; i < legends.size(); i++) {
//            Map<String,Object> legend = legends.get(i);
//            data.put("data" + i, JSON.toJSONString(dataList));
//            data.put("name" + i, legend.get("name").toString());
//        }
//        // 调用模板加载数据
//        String option = FreemarkerUtil.generate("EChartsLineOption.ftl", data);
//        return createImage(option);
    }

    public static String createLineStep(String title, List<String> dataX, List<String> dataY, List<Integer> data) throws ClientProtocolException, IOException {
        com.beyongx.echarts.Option option = new com.beyongx.echarts.Option();
        com.beyongx.echarts.options.Title beTitle = new com.beyongx.echarts.options.Title();
        beTitle.setText(title);
        option.title(beTitle);

        com.beyongx.echarts.options.XAxis xAxis = new com.beyongx.echarts.options.XAxis();
        xAxis.setType("category");
        xAxis.setData(dataX.toArray());
        option.xAxis(xAxis);

        com.beyongx.echarts.options.YAxis yAxis = new com.beyongx.echarts.options.YAxis();
        yAxis.setType("category");
        yAxis.setData(dataY.toArray());
        option.yAxis(yAxis);

        com.beyongx.echarts.charts.Line line = new com.beyongx.echarts.charts.Line();
        line.setName(title);
        line.setStep("start");
        Map<String,Object> lineStyleMap = new HashMap<>();
        lineStyleMap.put("width",100);
        line.setLineStyle(lineStyleMap);
        line.setData(data.toArray());
        option.addSeries(line);

        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        return createImage(gson.toJson(option));
    }

    public static String createImage(String optionStr){
//        String imgUrl = "/home/sunfu_back/uploadPath";
//        String imgUrl = "E:/uploadPath";
//        String requestUrl = "http://localhost:6666";
//        String imageName = "1575404577028849664.png";
//        // 根据option参数发起请求，转换为base64
//        String imagePath = ImageUtil.exportToImage(option,imgUrl,imageName);
//        return imagePath;
//        String optionStr = JSONObject.toJSONString(option);
        log.info("option：" + optionStr);
        String imgUrl = "/home/sunfu_back/uploadPath/";
//        String imgUrl = "C:/msznyl/uploadPath/";
        String requestUrl = "http://localhost:9090";
        String imageName = new IdWorker().nextId() + ".png";
        // 根据option参数发起请求，转换为base64
        try {
            String base64 = com.ruoyi.common.utils.phantomjs.EchartsUtil.generateEchartsBase64(optionStr, requestUrl);
            log.info("bar图片：" + imageName);
            File file = FileUtil.generateImage(base64, imgUrl + imageName);
        }catch (Exception e){
            log.error("发生了异常，" + e.getMessage());
        }
        return "https://sunfu.xdkdate.com/profile/" + imageName;
//        return "https://www.bythealthy.com/sunfu/profile/" + imageName;
    }
}
